import 'package:flutter/material.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:shenling_logistics/pages/task/components/noTaskComp.dart';
import 'package:shenling_logistics/pages/task/components/taskItem.dart';
import 'package:shenling_logistics/utils/eventBus.dart';
import 'package:shenling_logistics/utils/http.dart';
import 'package:shenling_logistics/utils/toast.dart';

class PendingTaskPage extends StatefulWidget {
  const PendingTaskPage({super.key});

  @override
  State<PendingTaskPage> createState() => _PendingTaskPageState();
}

class _PendingTaskPageState extends State<PendingTaskPage> {
  // 待提货任务列表数据
  List pendingTaskList = [];
  int _page = 1;
  bool _noMore = false;
  final EasyRefreshController _refreshController = EasyRefreshController();

  @override
  void initState() {
    super.initState();
    // 调用获取任务列表数据方法
    getPendingTaskData();
    // 注册订阅事件，登录成功后，刷新数据
    eventBus.on<LoginSuccessEvent>().listen((event) {
      getPendingTaskData();
    });
  }

  // 定义获取待提货任务列表数据
  Future<void> getPendingTaskData({bool isRefresh = false}) async {
    if (isRefresh) {
      setState(() {
        pendingTaskList = [];
        _page = 1;
        _noMore = false;
      });
      _refreshController.resetLoadState();
    }

    if (_noMore && !isRefresh) {
      _refreshController.finishLoad(noMore: true);
      return;
    }
    try {
      if (pendingTaskList.length >= 30) {
        ToastUtil.showInfo('没有更多数据了...');
        return;
      }
      final res = await http.get(
        '/driver/tasks/list',
        params: {'page': _page, 'pageSize': 10, 'status': 1},
      );
      if (res['code'] != 200) return ToastUtil.showError('获取任务列表数据失败');
      // 数据赋值
      setState(() {
        pendingTaskList.addAll(res['data']['items']);
      });
      // 页面+1
      _page++;
    } catch (e) {
      ToastUtil.showError('获取任务列表数据，网络出现错误');
    }
    if (isRefresh) {
      _refreshController.finishRefresh();
      _refreshController.resetLoadState();
    } else {
      _refreshController.finishLoad(noMore: _noMore);
    }
  }

  @override
  Widget build(BuildContext context) {
    return pendingTaskList.isEmpty
        ? NoTaskComp(title: '无待提货物')
        : Container(
            padding: EdgeInsets.only(left: 15, right: 15),
            color: Color.fromARGB(255, 244, 244, 244),
            child: EasyRefresh(
              controller: _refreshController,
              header: ClassicalHeader(
                refreshText: '下拉刷新',
                refreshReadyText: '释放刷新',
                refreshingText: '正在刷新...',
                refreshedText: '刷新完成',
                infoText: '上次更新 %T',
                bgColor: Colors.transparent,
                textColor: Colors.black87,
              ),
              footer: ClassicalFooter(
                loadText: '上拉加载',
                loadReadyText: '释放加载',
                loadingText: '正在加载...',
                loadedText: '加载完成',
                noMoreText: '没有更多数据',
                infoText: '上次加载 %T',
                bgColor: Colors.transparent,
                textColor: Colors.black87,
              ),
              onRefresh: () async {
                await getPendingTaskData(isRefresh: true);
              },
              onLoad: () async {
                await getPendingTaskData();
              },
              child: ListView.builder(
                padding: EdgeInsets.only(top: 15),
                itemBuilder: (BuildContext context, int index) {
                  return TaskItemComp(taskItem: pendingTaskList[index]);
                },
                itemCount: pendingTaskList.length,
              ),
            ),
          );
  }
}
